const { createApp } = Vue;

createApp({
    data() {
        return {
            templates: [],
            categories: [], // 存储分类列表用于筛选
            currentPage: 1,
            pageSize: 10,
            totalTemplates: 0,
            searchKey: '',
            form: {
                id: null,
                name: '',
                price: 0,
            },
            downloadModal: null,
            currentTemplate: null,
            downloadOptions: {
                status: '',
                dateType: 'today',
                startDate: new Date().toISOString().split('T')[0],
                endDate: new Date().toISOString().split('T')[0]
            },
            downloadCount: 0,
            updating: null, // 记录正在更新状态的模板ID
        }
    },
    computed: {
        totalPages() {
            return Math.ceil(this.totalTemplates / this.pageSize);
        },
        pageNumbers() {
            const pages = [];
            let start = Math.max(1, this.currentPage - 2);
            let end = Math.min(this.totalPages, start + 4);
            
            if (end - start < 4) {
                start = Math.max(1, end - 4);
            }
            
            for (let i = start; i <= end; i++) {
                pages.push(i);
            }
            return pages;
        }
    },
    watch: {
        'downloadOptions.status'() {
            this.updateDownloadCount();
        },
        'downloadOptions.dateType'() {
            this.updateDownloadCount();
        },
        'downloadOptions.startDate'() {
            if (this.downloadOptions.dateType === 'custom') {
                this.updateDownloadCount();
            }
        },
        'downloadOptions.endDate'() {
            if (this.downloadOptions.dateType === 'custom') {
                this.updateDownloadCount();
            }
        }
    },
    methods: {
        async loadTemplates() {
            try {
                // 模拟API调用
                const response = await fetch(`/api/admin/templates?search=${this.searchKey}`);
                const data = await response.json();
                
                // 模拟数据
                this.templates = data.data;
                this.totalTemplates = data.total;
            } catch (error) {
                console.error('加载模板数据失败:', error);
                alert('加载模板数据失败，请刷新重试');
            }
        },
        changePage(page) {
            if (page < 1 || page > this.totalPages) return;
            this.currentPage = page;
            this.loadTemplates();
        },
        searchTemplates() {
            this.currentPage = 1;
            this.loadTemplates();
        },
        handleAdd() {
            // 跳转到新增模板页面
            window.location.href = 'template-add.html';
        },
        handleEdit(template) {
            Swal.fire({
                title: '编辑奖励金额',
                html: `
                    <form id="editForm" class="text-start">
                        <div class="mb-3">
                            <label class="form-label">模板名称</label>
                            <input type="text" class="form-control" value="${template.name}" disabled>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">奖励金额（元）</label>
                            <div class="input-group">
                                <span class="input-group-text">¥</span>
                                <input type="number" 
                                       class="form-control" 
                                       id="priceInput"
                                       value="${(template.price / 100).toFixed(2)}"
                                       min="0" 
                                       step="0.01">
                            </div>
                            <div class="form-text text-muted">
                                用户爆料审核通过后将获得此金额奖励
                            </div>
                        </div>
                    </form>
                `,
                showCancelButton: true,
                confirmButtonText: '保存',
                cancelButtonText: '取消',
                preConfirm: () => {
                    const priceInput = document.getElementById('priceInput');
                    const price = parseFloat(priceInput.value);
                    
                    if (isNaN(price) || price < 0) {
                        Swal.showValidationMessage('请输入有效的金额');
                        return false;
                    }
                    
                    return {
                        price: Math.round(price * 100) // 转换为分
                    };
                }
            }).then(async (result) => {
                if (result.isConfirmed) {
                    try {
                        const response = await fetch(`/api/admin/template/${template.id}`, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                name: template.name, // 保持原名称不变
                                price: result.value.price
                            })
                        });

                        const data = await response.json();
                        if (data.code === 200) {
                            Swal.fire({
                                icon: 'success',
                                title: '保存成功',
                                showConfirmButton: false,
                                timer: 1500
                            });
                            this.loadTemplates(); // 重新加载列表
                        } else {
                            throw new Error(data.msg || '保存失败');
                        }
                    } catch (error) {
                        console.error('保存失败:', error);
                        Swal.fire({
                            icon: 'error',
                            title: '保存失败',
                            text: error.message || '请重试'
                        });
                    }
                }
            });
        },
        handleDelete(template) {
            if (confirm(`确定要删除模板"${template.name}"吗？此操作不可恢复！`)) {
                // 调用删除API
                alert('删除成功');
                this.loadTemplates();
            }
        },
        // 显示编辑弹窗
        showEditDialog() {
            Swal.fire({
                title: this.form.id ? '编辑模板' : '添加模板',
                html: `
                    <form id="templateForm" class="text-start">
                        <div class="mb-3">
                            <label class="form-label">模板名称</label>
                            <input type="text" class="form-control" id="templateName" 
                                   value="${this.form.name}" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">奖励金额（元）</label>
                            <div class="input-group">
                                <span class="input-group-text">¥</span>
                                <input type="number" class="form-control" id="templatePrice" 
                                       value="${(this.form.price / 100).toFixed(2)}"
                                       min="0" step="0.01" required>
                            </div>
                            <div class="form-text text-muted">
                                用户爆料审核通过后将获得此金额奖励
                            </div>
                        </div>
                        <!-- ... 其他表单字段 ... -->
                    </form>
                `,
                showCancelButton: true,
                confirmButtonText: '保存',
                cancelButtonText: '取消',
                preConfirm: () => {
                    const form = document.getElementById('templateForm');
                    if (!form.checkValidity()) {
                        form.reportValidity();
                        return false;
                    }
                    
                    return {
                        name: document.getElementById('templateName').value,
                        price: Math.round(document.getElementById('templatePrice').value * 100), // 转换为分
                        // ... 其他字段
                    };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    this.saveTemplate(result.value);
                }
            });
        },
        // 保存模板
        async saveTemplate(formData) {
            try {
                const url = this.form.id ? 
                    `/api/admin/template/${this.form.id}` : 
                    '/api/admin/template';

                const res = await fetch(url, {
                    method: this.form.id ? 'PUT' : 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        name: formData.name,
                        price: formData.price,
                        // ... 其他字段
                    })
                });

                const data = await res.json();
                if (data.code === 200) {
                    Swal.fire({
                        icon: 'success',
                        title: '保存成功',
                        showConfirmButton: false,
                        timer: 1500
                    });
                    this.loadTemplates();
                } else {
                    throw new Error(data.msg || '保存失败');
                }
            } catch (error) {
                console.error('保存模板失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: '保存失败',
                    text: error.message || '请重试'
                });
            }
        },
        handleDownload(template) {
            this.currentTemplate = template;
            this.downloadOptions = {
                status: '',
                dateType: 'today',
                startDate: new Date().toISOString().split('T')[0],
                endDate: new Date().toISOString().split('T')[0]
            };
            this.downloadCount = 0;
            this.downloadModal.show();
            this.$nextTick(() => {
                this.updateDownloadCount();
            });
        },
        showCategoryName(categoryId) {
            const category = this.categories.find(c => c.id === categoryId);
            return category ? category.name : '未知';
        },
        closeDownloadModal() {
            if (this.downloadModal) {
                this.downloadModal.hide();
                // 重置选项
                this.downloadOptions = {
                    status: '',
                    dateType: 'today',
                    startDate: new Date().toISOString().split('T')[0],
                    endDate: new Date().toISOString().split('T')[0]
                };
            }
        },
        async confirmDownload() {
            if (!this.currentTemplate) return;

            try {
                // 验证日期范围
                if (this.downloadOptions.dateType === 'custom') {
                    if (!this.downloadOptions.startDate || !this.downloadOptions.endDate) {
                        Swal.fire({
                            icon: 'warning',
                            title: '请选择日期范围',
                            text: '开始日期和结束日期都不能为空'
                        });
                        return;
                    }
                    if (this.downloadOptions.startDate > this.downloadOptions.endDate) {
                        Swal.fire({
                            icon: 'warning',
                            title: '日期范围错误',
                            text: '开始日期不能大于结束日期'
                        });
                        return;
                    }
                }

                // 构建下载参数
                const params = new URLSearchParams({
                    template_id: this.currentTemplate.id
                });

                if (this.downloadOptions.status) {
                    params.append('status', this.downloadOptions.status);
                }

                if (this.downloadOptions.dateType === 'today') {
                    params.append('date', new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toISOString().split('T')[0]);
                } else {
                    params.append('start_date', this.downloadOptions.startDate);
                    params.append('end_date', this.downloadOptions.endDate);
                }

                // 显示下载中提示
                Swal.fire({
                    title: '正在准备下载...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                // 发起下载请求
                const response = await fetch(`/api/admin/template/download?${params.toString()}`);
                if (!response.ok) {
                    throw new Error('下载失败');
                }
                const blob = await response.blob();
                
                // 创建下载链接
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `template_${this.currentTemplate.id}_${new Date().getTime()}.csv`;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);

                this.closeDownloadModal();
                Swal.fire({
                    icon: 'success',
                    title: '下载成功',
                    showConfirmButton: false,
                    timer: 1500
                });
            } catch (error) {
                console.error('下载失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: '下载失败',
                    text: '请稍后重试'
                });
            }
        },
        // 添加获取统计数据的方法
        async getTemplateStats(templateId, dateRange) {
            try {
                const params = new URLSearchParams({
                    template_id: templateId,
                    date_range: dateRange
                });
                
                const response = await fetch(`/api/admin/template/stats?${params}`);
                const data = await response.json();
                
                if (data.code === 200) {
                    return data.count;
                }
                throw new Error(data.msg || '获取统计数据失败');
            } catch (error) {
                console.error('获取统计数据失败:', error);
                return null;
            }
        },
        // 添加价格编辑方法
        async handlePriceEdit(template) {
            const { value: price } = await Swal.fire({
                title: '修改价格',
                input: 'number',
                inputLabel: '请输入新的价格（元）',
                inputValue: (template.price / 100).toFixed(2),
                inputAttributes: {
                    min: 0,
                    step: '0.01'
                },
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            });

            if (price !== undefined) {
                try {
                    const response = await fetch('/api/admin/template/update', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            id: template.id,
                            price: Math.round(price * 100)
                        })
                    });

                    const data = await response.json();
                    if (data.code === 200) {
                        Swal.fire({
                            icon: 'success',
                            title: '修改成功',
                            showConfirmButton: false,
                            timer: 1500
                        });
                        this.getTemplates(); // 刷新列表
                    } else {
                        throw new Error(data.msg || '修改失败');
                    }
                } catch (error) {
                    console.error('修改价格失败:', error);
                    Swal.fire({
                        icon: 'error',
                        title: '修改失败',
                        text: error.message || '请重试'
                    });
                }
            }
        },
        // 添加任务限制编辑方法
        async handleLimitEdit(template) {
            const { value: limit } = await Swal.fire({
                title: '修改任务限制',
                input: 'number',
                inputLabel: '请输入单用户任务次数限制（0表示不限制）',
                inputValue: template.user_task_limit || 0,
                inputAttributes: {
                    min: 0,
                    step: '1'
                },
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputValidator: (value) => {
                    if (value < 0) {
                        return '任务限制次数不能小于0';
                    }
                }
            });

            if (limit !== undefined) {
                try {
                    const response = await fetch('/api/admin/template/update', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            id: template.id,
                            user_task_limit: parseInt(limit)
                        })
                    });

                    const data = await response.json();
                    if (data.code === 200) {
                        Swal.fire({
                            icon: 'success',
                            title: '修改成功',
                            showConfirmButton: false,
                            timer: 1500
                        });
                        this.loadTemplates(); // 刷新列表
                    } else {
                        throw new Error(data.msg || '修改失败');
                    }
                } catch (error) {
                    console.error('修改任务限制失败:', error);
                    Swal.fire({
                        icon: 'error',
                        title: '修改失败',
                        text: error.message || '请重试'
                    });
                }
            }
        },
        async updateDownloadCount() {
            if (!this.currentTemplate) return;

            try {
                console.log('正在获取数据统计...'); // 添加调试日志
                // 构建查询参数
                const params = new URLSearchParams({
                    template_id: this.currentTemplate.id
                });

                if (this.downloadOptions.status) {
                    params.append('status', this.downloadOptions.status);
                }

                if (this.downloadOptions.dateType === 'today') {
                    // 获取北京时间
                    const date = new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toISOString().split('T')[0];
                    params.append('date', date);
                } else {
                    params.append('start_date', this.downloadOptions.startDate);
                    params.append('end_date', this.downloadOptions.endDate);
                }

                const response = await fetch(`/api/admin/template/download/count?${params.toString()}`);
                const data = await response.json();
                console.log('获取到的统计数据:', data); // 添加调试日志

                if (data.code === 200) {
                    this.downloadCount = data.count;
                } else {
                    throw new Error(data.msg || '获取数据统计失败');
                }
            } catch (error) {
                console.error('获取数据统计失败:', error);
                this.downloadCount = 0;
            }
        },
        async toggleTemplateStatus(template) {
            try {
                this.updating = template.id;
                const newStatus = template.is_open == 1 ? '0' : '1';
                
                const response = await fetch('/api/admin/template/update', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        id: template.id,
                        is_open: newStatus
                    })
                });

                const data = await response.json();
                
                if (data.code === 200) {
                    template.is_open = newStatus;
                    const statusText = newStatus == '1' ? '开启' : '关闭';
                    Swal.fire({
                        icon: 'success',
                        title: `模板已${statusText}`,
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 1500
                    });
                } else {
                    throw new Error(data.msg || '操作失败');
                }
            } catch (error) {
                console.error('切换模板状态失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: '操作失败',
                    text: error.message || '请重试'
                });
                // 恢复原状态
                template.is_open = template.is_open == 1 ? '0' : '1';
            } finally {
                this.updating = null;
            }
        },
        async loadCategories() {
            try {
                const response = await fetch('/api/admin/categories/all');
                const data = await response.json();
                if (data.code === 200) {
                    this.categories = data.data;
                    this.loadTemplates();
                }
            } catch (error) {
                console.error('加载分类列表失败:', error);
            }
        }
    },
    mounted() {
        
        this.loadCategories();
        // 初始化所有工具提示
        this.$nextTick(() => {
            const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });
            // 初始化模态框
            const modalElement = document.getElementById('downloadModal');
            if (modalElement) {
                this.downloadModal = new bootstrap.Modal(modalElement, {
                    backdrop: 'static',
                    keyboard: false
                });
            }
        });
    }
}).mount('#templateApp'); 